Convert to Epoch Time
Description
The convert_to_epoch function converts a date string into Unix epoch time (timestamp). It parses the input date string into a datetime object and converts it to the equivalent number of seconds since January 1, 1970, 00:00:00 UTC. Optionally, it can handle dates that are already in UTC.
Function Signature:
def convert_to_epoch(date_string: str, is_already_utc: bool = False):
Parameters
- date_string (
str): The date string to convert, in the formatYYYY-MM-DD HH:MM:SS. - is_already_utc (
bool, default=False): A flag indicating whether the input date is already in UTC. IfTrue, the date is treated as UTC; otherwise, it is assumed to be local time.
Returns
- int: The corresponding epoch time (Unix timestamp) as an integer. If the input is invalid, it returns
0.
Example Usage
epoch_time = convert_to_epoch('2025-04-09 15:30:00', is_already_utc=True)
print(epoch_time)
Notes
- The function expects the input date string to follow the format
YYYY-MM-DD HH:MM:SS. - If the
is_already_utcflag is set toTrue, the function assumes the input date string is in UTC and adjusts thedatetimeobject accordingly. - If the date string does not match the expected format, or any error occurs, the function returns
0.
Error Handling
- If an exception occurs while parsing the date string or converting it to epoch time, the function silently returns
0without raising any error.